<template>
  <div class="approval-history">
    <div class="search-bar">
      <el-input
          v-model="searchKey"
          placeholder="搜索历史审批"
          style="width: 300px; margin-right: 10px;"
          clearable
      />
      <el-select
          v-model="filterStatus"
          placeholder="筛选他人审批项状态"
          style="width: 170px; margin-right: 10px"
          clearable
          @change="getRecords"
          :disabled="isThird(radio)"
      >
        <el-option
            v-for="(text, key) in statusTextMap"
            :key="key"
            :label="text"
            :value="key"
        />
      </el-select>
      <el-radio-group v-model="radio" @change="getRecords">
        <el-radio-button label="所有" value=0 />
        <el-radio-button label="本人" value=1 />
        <el-radio-button label="他人" value=2 />
      </el-radio-group>
      <el-button type="primary" style="margin-left: 1vh" @click="getRecords">搜索</el-button>
    </div>

    <el-table
        :data="historyData"
        style="width: 180vh;border-radius: 10px"
    >
      <el-table-column  label="审批项" width="150">
        <template #default="{row}">
          <div class="type-tag">
            {{ row.processName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column  label="具体事项" width="240">
        <template #default="{row}">
          <div class="type-tag">
            {{ row.approvalInstance?.formData.title }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{row}">
          <el-tag
              :type="statusTypeMap[row.approvalInstance?.status]"
              effect="light"
          >
            {{ statusTextMap[row.approvalInstance?.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="startName" label="申请人" width="160"/>
      <el-table-column prop="approvalInstance.createTime" label="申请时间" width="190">
      </el-table-column>
      <el-table-column prop="currentStepTime" label="完成时间" width="190"/>
      <el-table-column label="操作" width="125">
        <template #default="{row}">
          <el-button
              type="primary"
              @click="startA(row)"
          >
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        v-model:page-size="pageSize"
        v-model:current-page= "pageCount"
        @change="getRecords"
        class="mt-4"
        style="display: flex; justify-content: center;margin-top: 2vh"
    />
    <!-- 审批详情对话框 -->
    <el-dialog
        v-model="detailVisible"
        width="1000"
        @before-close="detailVisible = false"
    ><div ref="captureRef">
      <!-- 审批概览 -->
      <el-card class="overview-card">
        <div class="overview-header" style="font-size: 20px;margin-bottom: 2vh">
          {{ nums.processName }}
          <el-tag v-if="!isDow" :type="statusTypeMap[nums.approvalInstance?.status]" effect="dark">
            {{ statusTextMap[nums.approvalInstance?.status] }}
          </el-tag>
        </div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="审批编号">
            {{ nums.approvalInstance?.processId }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ dayjs(nums.approvalInstance?.createTime).format('YYYY-MM-DD HH:mm') }}
          </el-descriptions-item>
          <el-descriptions-item label="申请人">
            {{nums.startName }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 审批进度 -->
      <el-card class="progress-card">
        <template #header>
          <div class="card-title">审批进度</div>
        </template>
        <el-steps direction="vertical" :active="1">
          <el-step
              v-for="(step, index) in approvalRecord"
              :key="index"
              :title="step.title"
              :status="getStatus(step.decision)"
              >
            <template #description>
              <div class="step-detail">
                <div v-if="step.approveId===userInfo.info.id">处理人：本人</div>
                <div v-else>处理人：{{ step.approveName }}</div>
                <div>审批要求：{{num?.approvalSteps[index]?.requirement}}</div>
                <div>审批意见：{{ step.comment }}</div>
                <div >处理时间：{{step.approveTime }}</div>
              </div>
            </template>
          </el-step>
        </el-steps>
      </el-card>

      <!-- 审批表单数据 -->
      <el-card class="form-data-card">
        <template #header>
          <div class="card-title">申请信息</div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="审批事由">
            {{ formData.title }}
          </el-descriptions-item>

          <template v-for="(value, key) in formData.fields" :key="key">
            <el-descriptions-item :label="fieldLabelMap[key]" v-if="key === 'daterange' && formData.fields.daterange!==''">
              <el-date-picker
                  v-model="formData.fields.daterange"
                  type="datetimerange"
                  start-placeholder="Start date"
                  end-placeholder="End date"
                  format="YYYY-MM-DD HH:mm:ss"
                  date-format="YYYY/MM/DD ddd"
                  time-format="A hh:mm:ss"
                  readonly="true"
              />
            </el-descriptions-item>
            <el-descriptions-item :label="fieldLabelMap[key]" v-if="key === 'file' &&  formData.fields.file!==''">
              <div class="el-upload__tip" v-for="(name,index) in  formData.fields.file">
                <el-link type="warning" @click="loadFile(name.name)">{{name.name.split('/').pop()}}</el-link>
              </div>
            </el-descriptions-item>
            <el-descriptions-item :label="fieldLabelMap[key]" v-if="key === 'text' &&  formData.fields.text!==''">
              {{ formData.fields.text}}
            </el-descriptions-item>
            <el-descriptions-item :label="fieldLabelMap[key]" v-if="key === 'number' &&  formData.fields.number!==''">
              {{  formData.fields.number}}
            </el-descriptions-item>
          </template>

          <el-descriptions-item label="详细说明">
            {{  formData.description }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card></div>
      <el-button @click="downloadWithWatermark(statusTextMap[nums.approvalInstance?.status])" style="margin-left: 50vh">下载为图片保存</el-button>
    </el-dialog>
  </div>
</template>

<script setup >
import { ref, computed } from 'vue'
import useUserInfoStore from "@/stores/userInfo.js";
import {getHisRecords} from "@/api/AInstance.js";
import dayjs from "dayjs";
import {getUserName} from "@/api/user.js";
import {getConfigInfo} from "@/api/Approval.js";
import {getRecord} from "@/api/record.js";
import html2canvas from "html2canvas";
import {ElMessage} from "element-plus";
import OSS from "ali-oss";
import {getToken} from "@/api/load.js";
const userInfo = useUserInfoStore()
const searchKey = ref('')
const filterStatus = ref('')
const detailVisible = ref(false)
const currentDetail = ref({})
const radio = ref(0)
const pageSize = ref(4)
const total = ref(1)
const pageCount = ref(Math.ceil(total.value / pageSize.value))
// 历史审批测试数据
const historyData = ref([
])
const isThird = (radio)=>{
  return radio!=='2'
}
const fieldLabelMap = {
  text: '信息描述',
  number: '数值',
  daterange: '时间范围',
  file: '附件材料'
}
const captureRef = ref(null);
const handleClose = ()=>{
  detailVisible.value = false
  nums.value = ref([])
  approvalRecord.value = ref([])
  formData.value = ref([])
}
// 下载处理函数
const downloadWithWatermark = async (status) => {
  try {
    // 1. 生成原始Canvas
    const canvas = await html2canvas(captureRef.value, {
      useCORS: true,
      scale: 2
    });

    // 2. 创建带水印的Canvas
    const watermarkCanvas = document.createElement('canvas');
    const ctx = watermarkCanvas.getContext('2d');

    // 设置Canvas尺寸与原始一致
    watermarkCanvas.width = canvas.width;
    watermarkCanvas.height = canvas.height;

    // 3. 绘制原始内容
    ctx.drawImage(canvas, 0, 0);

    // 4. 添加文字水印
    ctx.font = '40px Arial'; // 水印字体
    ctx.fillStyle = 'rgba(255, 0, 0, 0.3)'; // 半透明红色
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.save(); // 保存当前画布状态

    // 旋转水印角度
    ctx.translate(watermarkCanvas.width/2, watermarkCanvas.height/2);
    ctx.rotate(-30 * Math.PI / 180); // 旋转-30度
    ctx.fillText(dayjs().format('YYYYMMDDHHmm')+'下载；审批状态：'+status, -200, -200);
    ctx.restore(); // 恢复原始画布状态
    // 6. 转换为图片并下载
    const dataUrl = watermarkCanvas.toDataURL('image/png');
    const link = document.createElement('a');
    link.download = `watermarked-${Date.now()}.png`;
    link.href = dataUrl;
    link.click();

  } catch (error) {
    ElMessage.error('生成失败:', error);
  }
};
const getRecords = async ()=>{
  let sta=""
  if (filterStatus.value!==undefined){
    sta = filterStatus.value.toString().toLowerCase()
  }
  let res = await getHisRecords(userInfo.info.id,searchKey.value,sta,radio.value,pageCount.value,pageSize.value)

  if (res===undefined || res === null){
    historyData.value=null
    return
  }
  historyData.value = res.list
  for (let i = 0; i < historyData.value.length; i++) {
    historyData.value[i].approvalInstance.formData = JSON.parse(historyData.value[i].approvalInstance.formData)
  }

  total.value = res.total
}
// 保持原有状态映射
const statusTypeMap = {
  'RETRIEVE': 'info',
  'PENDING': 'warning',
  'APPROVED': 'success',
  'REJECTED': 'danger'
}

const statusTextMap = {
  'RETRIEVE': '已撤回',
  'PENDING': '审批中',
  'APPROVED': '已通过',
  'REJECTED': '已驳回'
}


const tagTypeMap = {
  '财务': 'success',
  '人事': 'warning',
  '行政': 'info'
}
const formData = ref()
const appUser = ref([])
const num = ref()
const nums = ref()
const getApprovalInfo = async (pid,id) => {
  let approval = await getConfigInfo(pid)
  if (approval !== undefined){
    num.value = approval
  }
  num.value.id = id
}
const approvalRecord = ref()
const getApprovalRecord = async (id) => {
  let decision = null
  approvalRecord.value = await getRecord(id,decision)
}
const getStatus = (status)=>{
  if(status==="APPROVED"){
    return 'success'
  }else if (status==='REJECTED'){
    return 'error'
  }else if (status==='PENDING'){
    return 'error'
  }else if (status==='RETRIEVE'){
    return 'process'
  }
}
const getSTSToken = async () => {
  return await getToken();
};
const initOSSClient = async () => {
  let credentials = await getSTSToken();
  return new OSS({
    region: 'oss-cn-hangzhou',
    accessKeyId: credentials.AccessKeyId,
    accessKeySecret: credentials.AccessKeySecret,
    stsToken: credentials.SecurityToken,
    bucket: 'web-framework10011',
    endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
    secure: true
  });}
const loadFile = async (file) => {
  try {
    let names = `${file}`
    const client = await initOSSClient();
    // 生成带签名的下载链接（1小时有效）
    const url = client.signatureUrl(names, {
      expires: 3600, // 有效期1小时（单位：秒）
      response: {
        'content-disposition': 'attachment' // 强制浏览器下载
      }
    });

    // 提取原始文件名（去除路径和时间戳）
    const fileNameWithTimestamp = names.split('/').pop();
    const originalFileName = fileNameWithTimestamp.split('_').slice(1).join('_');
    // 创建虚拟链接触发下载
    const link = document.createElement('a');
    link.href = url;
    link.download = originalFileName; // 设置下载文件名
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success('开始下载');
  } catch (err) {
    ElMessage.error('下载失败');
    console.error('Download Error:', err);
  }
};
const startA =async (row) => {
  await getApprovalInfo(row.approvalInstance.processId,row.approvalInstance.id)
  formData.value = row.approvalInstance.formData
  nums.value= row

  for (let i = 0; i < num.value.approvalSteps?.length; i++) {
    await getUserName(num.value.approvalSteps[i]?.approvePeople).then(result => {
      appUser.value[i] = num.value.approvalSteps[i]?.approveType + "/" + result
    })
  }
  await getApprovalRecord( row.approvalInstance.id)
  detailVisible.value = true;
}
getRecords()
</script>

<style scoped>
.approval-history {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  margin-top: 2vh
}

.type-tag {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 保持原有卡片样式 */
.overview-card,
.progress-card,
.form-data-card {
  margin-bottom: 20px;
}
</style>